//package com.wg.gateway.config;
//
//import cn.dev33.satoken.stp.StpUtil;
//import com.alibaba.nacos.shaded.com.google.gson.JsonObject;
//import org.springframework.cloud.gateway.filter.GatewayFilterChain;
//import org.springframework.cloud.gateway.filter.GlobalFilter;
//import org.springframework.core.Ordered;
//import org.springframework.core.io.buffer.DataBuffer;
//import org.springframework.http.HttpHeaders;
//import org.springframework.http.server.reactive.ServerHttpResponse;
//import org.springframework.stereotype.Component;
//import org.springframework.web.server.ServerWebExchange;
//import reactor.core.publisher.Mono;
//
//import java.nio.charset.StandardCharsets;
//import java.util.ArrayList;
//import java.util.List;
//
//import static cn.bdmcom.result.ResultCode.TOKEN_INVALID;
//import static cn.bdmcom.result.ResultCode.TOKEN_ISNULL;
//
//@Component
//public class SaTokenGatewayFilter implements GlobalFilter, Ordered {
//
//    @Override
//    public int getOrder() {
//        return -1000; // 设置更高的优先级，确保在其他过滤器之前执行
//    }
//
//    @Override
//    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        // 1.获取路径
//        String path = exchange.getRequest().getURI().getPath();
//        String method = exchange.getRequest().getMethod().name();
//
//        System.out.println("=== Sa-Token Gateway Filter ===");
//        System.out.println("Request path: " + path);
//        System.out.println("Request method: " + method);
//
//
//        // 白名单路径
//        List<String> whiteList = new ArrayList<>();
//        whiteList.add("/user/login");
//        whiteList.add("/user/register");
//        whiteList.add("/user/getUserByUserName/");
//        whiteList.add("/user/getUserByEmail/");
//        whiteList.add("/user/sendEmail/");
//        // 注意：这里移除了 "/user"，因为登录接口是 "/user" GET 方法，需要特殊处理
//
//        // 特殊处理登录接口
//        if ("/user".equals(path) && "GET".equals(method)) {
//            System.out.println("Allowing login endpoint: GET /user");
//            return chain.filter(exchange);
//        }
//
//        // 检查是否在白名单中
//        boolean isWhitelisted = false;
//        for (String whitePath : whiteList) {
//            if (path.startsWith(whitePath)) {  // 前缀匹配
//                isWhitelisted = true;
//                break;
//            }
//        }
//
//        System.out.println("Is whitelisted: " + isWhitelisted);
//
//        // 如果在白名单中，直接放行
//        if (isWhitelisted) {
//            System.out.println("Allowing whitelisted path: " + path);
//            return chain.filter(exchange);
//        }
//
//        // 非白名单路径需要验证token
//        System.out.println("Path requires authentication: " + path);
//
//        // 从请求头中获取token
//        HttpHeaders headers = exchange.getRequest().getHeaders();
//        String token = headers.getFirst("Authorization");
//        System.out.println("Gateway token: " + token);
//
//        // token为空
//        if (token == null) {
//            System.out.println("Token is null, returning error");
//            return this.writeErrorResponse(exchange, Integer.parseInt(TOKEN_ISNULL.code), TOKEN_ISNULL.msg);
//        }
//
//        // 验证token
//        try {
//            Object loginId = StpUtil.getLoginIdByToken(token);
//            System.out.println("Gateway loginId: " + loginId);
//            if (loginId == null) {
//                System.out.println("Invalid token, returning error");
//                return this.writeErrorResponse(exchange, Integer.parseInt(TOKEN_INVALID.code), TOKEN_INVALID.msg);
//            }
//        } catch (Exception e) {
//            System.out.println("Token validation error: " + e.getMessage());
//            return this.writeErrorResponse(exchange, Integer.parseInt(TOKEN_INVALID.code), TOKEN_INVALID.msg);
//        }
//
//        System.out.println("Token validated successfully, allowing access");
//        return chain.filter(exchange);
//    }
//
//    private Mono<Void> writeErrorResponse(ServerWebExchange exchange, int code, String msg) {
//        ServerHttpResponse response = exchange.getResponse();
//        JsonObject message = new JsonObject();
//        message.addProperty("code", code);
//        message.addProperty("data", msg);
//        message.addProperty("msg", msg);
//        byte[] bytes = message.toString().getBytes(StandardCharsets.UTF_8);
//        DataBuffer buffer = response.bufferFactory().wrap(bytes);
//        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
//        System.out.println("Returning error response: code=" + code + ", msg=" + msg);
//        return response.writeWith(Mono.just(buffer));
//    }
//}
